#include "configuration.h"
#include <sstream>
#include <iostream>
#include <stdio.h>

Configuration::Configuration(){
  folderList_ = new std::vector<std::string>();
}
Configuration::~Configuration(){
  delete folderList_;
}
void Configuration::ReadConfigFile(std::string path)
{
   static char filename[] = "/home/curlymaster/projets/gushare/usharer.conf";
   FILE *file = fopen ( filename, "r" );
   if ( file != NULL )
   {
      char line [ 128 ]; /* or other suitable maximum line size */
      while ( fgets ( line, sizeof line, file ) != NULL ) /* read a line */
      {
         AnalyseLine(line);
      }
      fclose ( file );
   }
   else
   {
      perror ( filename ); /* why didn't the file open? */
   }
}

void Configuration::WriteConfigFile(std::string path)
{
        static char filename[] = "/home/curlymaster/projets/gushare/wusharer.conf";
        FILE *file = fopen ( filename, "w" );
        if ( file != NULL ){
                char line [ 128 ]; /* or other suitable maximum line size */
                for(int i = 0; i < NUMBEROFARGUMENT; i++){
                        
                }
                fclose ( file );
        }else{
                perror ( filename ); /* why didn't the file open? */
        }
}

void Configuration::AnalyseLine(std::string line)
{
  std::string arg;
  std::string value;
  char *current = '\0';
  if(line[0] == '#')
    return;
  for(int i = 0;i < line.size();i++) {
    if(line[i] == '=') {
      std::stringstream correctLine(line);
      getline(correctLine, arg, '=');
      getline(correctLine, value, '=');

      std::cout <<arg<<"="<<value << "\n";
      setArguments(arg, value);
      
    }
  }
}

void Configuration::setArguments(std::string arg, std::string value){
   if(arg == "USHARE_NAME")
      uShareName_ = value;
   else
    if(arg ==  "USHARE_IFACE")
      uShareIFace_ = value;
   else
    if(arg ==  "USHARE_PORT")
      uSharePort_ = value;
   else
    if(arg ==  "USHARE_TELNET_PORT")
      uShareTelnetPort_ = value;
   else
    if(arg ==  "USHARE_DIR"){
      std::stringstream pathList(value);
      for (std::string path; std::getline(pathList, path, ','); folderList_->push_back(path));
    }
   else
    if(arg ==  "USHARE_OVERRIDE_ICONV_ERR")
      uShareOverrideIConvErr_ = value;
   else
    if(arg ==  "USHARE_ENABLE_WEB")
      uShareEnableWeb_ = value;
   else
    if(arg ==  "USHARE_ENABLE_TELNET")
      uShareEnableTelnet_ = value;
   else
    if(arg ==  "USHARE_ENABLE_XBOX")
      uShareEnableXbox_ = value;
   else
    if(arg ==  "USHARE_ENABLE_DLNA")
      uShareEnableDlna_ = value;
  
  
}

std::vector<std::string> *Configuration::getFolderList(){
  //TODO change it to be more secure returning a copy of the real vector also setter that can add element
  return folderList_;
}